package com.trend.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.trend.pojo.IndexData;
import com.trend.service.BackTestService;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

@RestController
public class BackTestController {
    @Autowired BackTestService backTestService;
 
    @GetMapping("/simulate/{code}/{startDate}/{endDate}")
    @CrossOrigin
    public Map<String,Object> backTest(@PathVariable("code") String code,
    									@PathVariable("startDate") String strStartDate,
    									@PathVariable("endDate") String strEndDate) throws Exception {
    	
    	
        List<IndexData> allIndexDatas = backTestService.listIndexData(code);
        
        String indexStartDate = allIndexDatas.get(0).getDate();
        String indexEndDate = allIndexDatas.get(allIndexDatas.size() - 1).getDate();
        
        allIndexDatas = filterByDateRange( allIndexDatas, indexStartDate, indexEndDate);
        
        Map<String,Object> result = new HashMap<>();
        result.put("indexDatas", allIndexDatas);
        return result;
    }
    
   private List<IndexData> filterByDateRange(List<IndexData> allIndexDatas, String indexStartDate, String indexEndDate){
    	// "null".equals(strString) || "undefined".equals(strString)
	   if(StrUtil.isBlankOrUndefined(indexStartDate) || StrUtil.isBlankOrUndefined(indexEndDate)) 
		   return allIndexDatas;
	   
	   
	   List<IndexData> result = new ArrayList<>();
	   DateTime endDate = DateUtil.parse(indexEndDate);
	   DateTime startDate = DateUtil.parse(indexStartDate);
	   
	   for(IndexData indexData : allIndexDatas) {
		   DateTime indexDate = DateUtil.parse(indexData.getDate());
		   // 大于等于开始日期，小于等于结束日期
		   if(indexDate.getTime() >= startDate.getTime() && indexDate.getTime() <= endDate.getTime()) {
			   result.add(indexData);
		   }
	   }
	   
	   return result;
    }
}
